package com.itany.corejava.day14;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;

public class TestEdit implements ActionListener {
    private JFrame jf;

    private JMenuBar jmb;

    private JTextArea jta;

    private boolean wasSaved=true;

    private String filePath;

    public TestEdit() {
        jf=new JFrame("记事本");
        jta=new JTextArea(20,50);

        jmb=new JMenuBar();

        String[] jmLab={"文件","编辑","查看","帮助"};
        String[][] jmiLab={
                {"新建","打开","","保存","另存为","","退出"},
                {"撤销","","剪切","复制","粘贴","","查找","替换"},
                {},
                {"关于记事本"}
        };


        for (int i = 0; i < jmLab.length; i++) {
            JMenu jm=new JMenu(jmLab[i]);

            if ("查看".equals(jmLab[i])){
                JMenu jm2=new JMenu("缩放");
                JMenuItem biggerJmi=new JMenuItem("放大");
                JMenuItem smallerJmi=new JMenuItem("缩小");

                biggerJmi.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Font font=jta.getFont();
                        int style=font.getStyle();
                        int size=font.getSize();
                        jta.setFont(font.deriveFont(style,size+5));
                    }
                });

                smallerJmi.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Font font=jta.getFont();
                        int style=font.getStyle();
                        int size=font.getSize();
                        jta.setFont(font.deriveFont(style,size-5));
                    }
                });
                jm2.add(biggerJmi);
                jm2.add(smallerJmi);
                jm.add(jm2);
                jmb.add(jm);
                continue;
            }

            for (int j = 0; j < jmiLab[i].length; j++) {
                if("".equals(jmiLab[i][j])){
                    jm.addSeparator();
                }else {
                    JMenuItem jmi = new JMenuItem(jmiLab[i][j]);
                    jmi.addActionListener(this);
                    jm.add(jmi);
                }
            }

            jmb.add(jm);
        }
    }

    private void init(){
        jf.setJMenuBar(jmb);
        JScrollPane jsp=new JScrollPane(jta);
        jf.add(jsp);
    }

    private void addEventHandler(){
        jf.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {

                System.out.println("TestEdit.windowClosing");

                if(wasSaved==false){
                    int op=JOptionPane.showConfirmDialog(jf,"文件没有保存是否退出？","确认退出",JOptionPane.YES_NO_CANCEL_OPTION);
                    if(op!=JOptionPane.YES_OPTION){
                        return;
                    }
                }
                System.exit(0);

            }
        });

        jta.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                System.out.println("TestEdit.insertUpdate");

                wasSaved=false;
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                System.out.println("TestEdit.removeUpdate");

                wasSaved=false;
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                System.out.println("TestEdit.changedUpdate");

                wasSaved=false;
            }
        });
    }

    public void show(){
        init();
        addEventHandler();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TestEdit().show();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("TestEdit.actionPerformed");
        
        String cmd=e.getActionCommand();

        System.out.println("cmd = " + cmd);

        if("退出".equals(cmd)){
            if(wasSaved==false){
                int op=JOptionPane.showConfirmDialog(jf,"文件没有保存是否退出？","确认退出",JOptionPane.YES_NO_CANCEL_OPTION);
                if(op!=JOptionPane.YES_OPTION){
                    return;
                }
            }
            System.exit(0);

        }
        if("打开".equals(cmd)){
            FileDialog fd=new FileDialog(jf,"打开文件");
            fd.setVisible(true);
            if(fd.getFile()==null){
                return;
            }
            filePath=fd.getDirectory()+fd.getFile();

            BufferedReader br=null;

            try{

                br=new BufferedReader(
                        new InputStreamReader(
                                new FileInputStream(filePath),"utf-8"
                        )
                );

                String s;

                while((s=br.readLine())!=null){
                    jta.append(s+"\n");
                }

                wasSaved=true;

            }catch (Exception ex){
                JOptionPane.showMessageDialog(jf,"打开失败");
            }finally{
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }


        }
        if("保存".equals(cmd)){

            if(filePath==null){
                FileDialog fd=new FileDialog(jf,"另存为",FileDialog.SAVE);
                fd.setVisible(true);
                if(fd.getFile()==null){
                    return;
                }
                filePath=fd.getDirectory()+fd.getFile();
            }

            save();

            wasSaved=true;

        }
        if("另存为".equals(cmd)){
            FileDialog fd=new FileDialog(jf,"另存为",FileDialog.SAVE);
            fd.setVisible(true);
            if(fd.getFile()==null){
                return;
            }
            filePath=fd.getDirectory()+fd.getFile();

            save();

            wasSaved=true;
        }

    }

    private void save(){
        PrintWriter pw=null;
        try{

            pw=new PrintWriter(filePath);

            pw.print(jta.getText());

        }catch (Exception e){
            JOptionPane.showMessageDialog(jf,"保存失败");
        }finally{
            if(pw!=null){
                pw.close();
            }
        }
    }
}
